package view;

/*
Cours :             LOG120 
Session :           Saison (hiver) 
Groupe :            01 
Projet :            Laboratoire #2
Etudiant(e)(s) :    Jeremy Moreau
                    Alexandre Richard
                    Philippe Pigeon
Code(s) perm. :     MORJ91010106
					RICA10028806 
                    PIGP08058903
Professeur :        Ghizlane El Boussaidi  
Date remise :       2012-03-010  
*/

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import model.Commande;
import model.LigneCommande;

import controller.CommandeController;

@SuppressWarnings("serial")
public class CommandeView extends AbstractView implements ActionListener, ListSelectionListener
{
	CommandeViewer cViewer;
	JButton btRetirer, btCommander;
	JLabel lbTotal;

	public CommandeView(CommandeController _ctrl) 
	{
		super(_ctrl);
		
		setLayout(null);
		setBounds(270, 10, 180, 280);
		
		cViewer = new CommandeViewer();
		cViewer.setBounds(0, 0, 179, 181);
		cViewer.addListSelectionListener(this);
		
		btRetirer = new JButton("Retirer");
		btRetirer.setBounds(25, 205, 76, 23);
		btRetirer.setEnabled(false);
		btRetirer.addActionListener(this);
		
		btCommander = new JButton("Commander");
		btCommander.setBounds(8, 233, 110, 23);
		btCommander.setEnabled(false);
		btCommander.addActionListener(this);
		
		lbTotal = new JLabel("Total: ");
		lbTotal.setBounds(13, 180, 100, 23);
		
		add(cViewer);
		add(btRetirer);
		add(btCommander);
		add(lbTotal);
	}

	@Override
	public void update(Observable o, Object arg) 
	{
		Commande c = (Commande)o;
		
		cViewer.update(c);
		
		lbTotal.setText( String.format("Total: %5.2f $", ((Commande)o).getTotal() ) );
		
		if(cViewer.getModel().getSize() > 0)
			btCommander.setEnabled(true);
		else
			btCommander.setEnabled(false);
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == btRetirer)
		{
			if(cViewer.getSelectedIndex() > -1)
				try
				{  getCCtrl().retirerLigneCommande( (LigneCommande)cViewer.getSelectedValue() );   }
				catch(ClassCastException cce) {}
		}
		if(e.getSource() == btCommander)
		{
			if(cViewer.getModel().getSize() > 0)
			{
				getCCtrl().previewCommande();
			}
		}
		
	}

	@Override
	public void valueChanged(ListSelectionEvent e) 
	{
		if(cViewer.getSelectedIndex() == -1)
			btRetirer.setEnabled(false);
		else
			btRetirer.setEnabled(true);
		
	}

}
